<template>
    <div id='' class='my_tree'>
        <div class="ivu-p-8">
            <Input v-model="query" search placeholder="输入菜单名称搜索" @on-change="handleSearch" />
        </div>
        <div class="content">
            <Tree :data="menuList" check-strictly :render="renderContent" @on-select-change="handleSelectNode" @on-contextmenu="handleContextMenu">
                <!-- <Tree :data="menuList" show-checkbox check-strictly :render="renderContent" @on-select-change="handleSelectNode" @on-check-change="handleCheckNode" @on-contextmenu="handleContextMenu"> -->
                <template slot="contextMenu">
                    <DropdownItem @click.native="addMenu">添加子菜单</DropdownItem>
                    <DropdownItem divided @click.native="nodeDelete" style="color: #ed4014">删除</DropdownItem>
                </template>
            </Tree>
        </div>
    </div>
</template>
<script>
import { mapActions, mapState, mapGetters } from 'vuex'
export default {
    name: '',
    inject: ['provideClick'],
    props: [''],
    data() {
        return {
            menuList: [],
            menuListCopy: [],
            query: '',
        };
    },
    components: {},
    computed: {
        ...mapState('extend/sysMenu', ['$row'])
    },
    beforeMount() { },
    mounted() {
        this.getTree()
    },
    methods: {
        ...mapActions('extend/sysMenu', ['setData']),
        ...mapGetters('extend/sysMenu', ['getData']),
        getTree() {
            this.setData([{
                key: '$row',
                value: null
            }])
            this.$http.$get('getMenuTree', { params: {} }).then(res => {
                if (res.code == 200) {
                    this.menuListCopy = icu.util.deepClone(this.recurrenceTree(res.data))
                    this.menuList = icu.util.deepClone(this.recurrenceTree(res.data))
                }
            })
        },
        recurrenceTree(data) {
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                element['title'] = element.name
                element['value'] = element.id
                element['expand'] = true
                element['contextmenu'] = true
                if (element.children.length !== 0) {
                    this.recurrenceTree(element.children)
                }
            }
            return data
        },
        // 延展收起树
        togTree(event) {
            this.toggleTree(this.menuList, event)
            if (event) {
                this.menuList = icu.util.deepClone(this.menuListCopy)
            }
        },
        toggleTree(data, event) {
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                element['expand'] = event
                if (!element.children) {
                    element.children = []
                }
                if (element.children.length !== 0) {
                    this.toggleTree(element.children, event)
                }
            }
        },
        // 查询方法
        handleSearch() {
            const query = this.query;
            this.selectedData = [];
            if (query) {
                this.menuList = this.handleQueryNode(this.menuListCopy, query, []);
            } else {
                this.handleInitMenuList();
            }
        },
        handleInitMenuList() {
            this.menuList = icu.util.deepClone(this.menuListCopy)
        },
        handleQueryNode(menuList, query, queryList) {
            menuList.forEach(menu => {
                let newMenu = {};
                for (let i in menu) {
                    if (i !== 'children') newMenu[i] = menu[i];
                }
                if (newMenu.title.indexOf(query) > -1) queryList.push(newMenu);
                if (menu.children && menu.children.length) newMenu.children = [];
                menu.children && this.handleQueryNode(menu.children, query, queryList);
            });
            return queryList;
        },
        // 点击树节点触发
        handleSelectNode(item) {
            if (item.length == 0) {
                this.provideClick("default", { prop: item })
                return
            }
            if (item[0].type == null) {
                this.provideClick("default", { prop: item })
            } else {
                this.provideClick("编辑", { prop: item })
            }
        },
        // 当前节点点击右键时触发
        handleContextMenu(item) {
            this.setData([{
                key: "$row",
                value: item
            }])
        },
        // 新增菜单
        addMenu() {
            this.provideClick("右键新增", { prop: this.$row })
        },
        // 删除
        nodeDelete() {
            this.$Modal.confirm({
                title: '关闭确认',
                content: `您确认要删除菜单<strong>${this.$row.title}</strong>吗？`,
                onOk: () => {
                    this.$http.$get('deleteMenu', { params: { id: this.$row.id } }).then(res => {
                        if (res.code == 200) {
                            this.$Message.success('删除成功');
                            this.getTree()
                            this.provideClick("删除成功", {})
                        }
                    })
                }
            });
        },
        // 前台添加节点
        addNode() {
            let data = this.updateNode(this.menuListCopy)
            if (!this.query) {
                this.updateNode(this.menuList)
            } else {
                this.handleSearch()
            }
        },
        updateNode(data) {
            for (let i = 0; i < data.length; i++) {
                const element = data[i];
                // 根据$row定位添加的位置
                if (element.id == this.$row.id) {
                    let resD = this.getData()('respondData')
                    resD['title'] = resD.name
                    resD['value'] = resD.id
                    if (!element.children) {
                        element.children = [];
                    }
                    if (element.children.length == 0) {
                        element.children.push(resD)
                    } else {
                        // 然后根据respondData，添加到数组的指定位置，根据排序添加
                        element.children.push(resD)
                        element.children = element.children.sort(function (a, b) {
                            return a.sort * 1 - b.sort * 1;
                        })
                        // element.children.splice(element.sort * 1, 0, resD)
                    }
                    return
                }
                if (element.children.length !== 0) {
                    this.updateNode(element.children)
                }
            }
            return data
        },
        // 渲染树
        renderContent(h, { root, node, data }) {
            return h('span', {
                style: { display: 'inline-block', width: '100%', height: '22px', 'line-height': '22px' }
            }, [
                h('span', {
                    style: {
                        display: 'inline-block', //根据不同标签display值，有的不用加。
                        'justify-content': 'center',
                        'align-items': 'center',
                        height: '22px', 'line-height': '25px',
                        width: '200px',
                        'white-space': 'nowrap', //设置文字不换行
                        overflow: 'hidden', //这个是设置隐藏的。还有其他的，例如scroll，是超出固定长度，底部显示滚动条的。
                        'text-overflow': 'ellipsis', //这个就是设置直接隐藏掉文字，还是显示...的。当前是显示省略号。直接省略是clip
                    }
                }, [h('span', {
                    attrs: { title: data.title, class: 'text-over' },

                }, data.title)]),
                h('span', {
                    style: { display: 'inline-block', float: 'right', marginRight: '32px' }
                }, [
                    h('Tag', {
                        props: Object.assign({}, {
                            color: data.systemType == '0' ? 'blue' : 'green',//green
                        }),
                        style: { marginRight: '8px', marginTop: '-1px', height: '22px', 'line-height': '22px', display: data.systemType == null ? 'none' : 'inline-block' }
                    }, [
                        h('span', data.systemType == '0' ? '后台' : data.systemType == '1' ? '前台' : '')
                    ]),
                    h('Tag', {
                        props: Object.assign({}, {
                            color: data.type == '0' ? 'blue' : 'default' //default
                        }),
                        style: { height: '22px', marginTop: '-1px', 'line-height': '22px', display: data.type == null ? 'none' : 'inline-block' }
                    }, [
                        h('span', data.type == '0' ? '菜单' : data.type == '1' ? '按钮' : '')
                    ])
                ])
            ]);
        }
    },
    watch: {}
}
</script>
<style>
.my_tree .ivu-tree-title {
    width: 98%;
    line-height: 10px;
}
</style>
<style lang='less' scoped>
.my_tree .content {
    height: 660px;
    overflow-y: auto;
}
.my_tree .text-over {
    width: 200px;
    white-space: nowrap; //设置文字不换行
    overflow: hidden; //这个是设置隐藏的。还有其他的，例如scroll，是超出固定长度，底部显示滚动条的。
    text-overflow: ellipsis; //这个就是设置直接隐藏掉文字，还是显示...的。当前是显示省略号。直接省略是clip
    display: inline-block; //根据不同标签display值，有的不用加。
}
</style>